package minimum;

import projectcvip.*;

/**
 *
 * @author Michał
 */
public class MinimumWorker extends JSBasic
{

    public Integer f(Integer x)
    {
        return (-x);
    }

    public void worker()
    {
        try
        {
            System.out.println("Wykonawca zaczyna prace.");
            while (true)
            {
                Task task = new Task();
                task.a = null;
                task.b = null;
                //Transaction transaction = TransactionFactory.create(txnManager, defaultLease).transaction;
                System.out.println("Wykonawca pobiera zadanie...");
                task = (Task) space.take(task, null, defaultLease);
                if (task.a == null && task.b == null)
                {
                    //transaction.abort();
                    System.out.println("Wykonawca koncczy prace.");
                    return;
                }
                System.out.println("Wykonawca rozwiazuje: a = " + task.a + "; b = " + task.b + ";");
                Result result = work(task.a, task.b);
                space.write(result, null, defaultLease);
            //transaction.commit();
            }
        }
        catch (Exception ex)
        {
            System.out.println(ex);
        }
    }

    public Result work(Integer a, Integer b)
    {
        int min = Integer.MAX_VALUE;
        int x = 0;
        for (int i = a.intValue(); i <= b.intValue(); i++)
        {
            if (f(i) < min)
            {
                min = f(i);
                x = i;
            }
        }
        Result result = new Result();
        result.minY = new Integer(min);
        result.x = new Integer(x);
        return result;
    }

    public void run()
    {
        worker();
    }
}
